package com.skynet.supervision.config.jackson;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.skynet.supervision.utils.Strings;
import lombok.val;

import java.io.IOException;

public final class JacksonIntegerDeserializer extends JsonDeserializer<Integer> {
    public static final JacksonIntegerDeserializer INSTANCE = new JacksonIntegerDeserializer();

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
        val pt = p.currentToken();
        if (pt == JsonToken.VALUE_NULL) {
            return null;
        }
        if (pt != JsonToken.VALUE_NUMBER_INT) {
            throw new JsonParseException(p, Strings.sprintf(" {} 不是合法的整数参数", p.getCurrentName()));
        }
        val vstr = p.getText();
        if (Strings.isEmpty(vstr)) {
            return null;
        }
        try {
            return Integer.parseInt(vstr);
        } catch (Exception ex) {
            throw new JsonParseException(p, Strings.sprintf(" {} 不是合法的整数参数", p.getCurrentName()), ex);
        }
    }
}
